const express = require('express');
const cors = require('cors');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.json());

// 存储激活码的JSON文件
const LICENSE_FILE = path.join(__dirname, 'licenses.json');

// 初始化许可证文件
function initLicenseFile() {
    if (!fs.existsSync(LICENSE_FILE)) {
        fs.writeFileSync(LICENSE_FILE, JSON.stringify([], null, 2));
    }
}

// 读取许可证数据
function readLicenses() {
    try {
        const data = fs.readFileSync(LICENSE_FILE, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error('读取许可证文件失败:', error);
        return [];
    }
}

// 保存许可证数据
function saveLicenses(licenses) {
    try {
        fs.writeFileSync(LICENSE_FILE, JSON.stringify(licenses, null, 2));
        return true;
    } catch (error) {
        console.error('保存许可证文件失败:', error);
        return false;
    }
}

// 生成机器码
function generateMachineId() {
    const os = require('os');
    const networkInterfaces = os.networkInterfaces();
    const macAddress = Object.values(networkInterfaces)
        .flat()
        .find(interface => !interface.internal && interface.mac !== '00:00:00:00:00:00')?.mac || 'unknown';
    
    return crypto.createHash('md5').update(macAddress + os.hostname()).digest('hex');
}

// 验证激活码API
app.post('/api/verify', (req, res) => {
    const { license_key, machine_id } = req.body;
    
    if (!license_key || !machine_id) {
        return res.status(400).json({
            valid: false,
            message: '缺少必要参数'
        });
    }
    
    const licenses = readLicenses();
    const license = licenses.find(l => l.license_key === license_key);
    
    if (!license) {
        return res.json({
            valid: false,
            message: '激活码不存在'
        });
    }
    
    // 检查是否过期
    const now = new Date();
    const expireDate = new Date(license.expire_date);
    
    if (now > expireDate) {
        return res.json({
            valid: false,
            message: '激活码已过期',
            expire_date: license.expire_date
        });
    }
    
    // 检查机器绑定（可选，这里暂时不强制绑定）
    if (license.machine_id && license.machine_id !== machine_id) {
        return res.json({
            valid: false,
            message: '激活码已绑定其他设备'
        });
    }
    
    // 如果没有绑定机器，则绑定当前机器
    if (!license.machine_id) {
        license.machine_id = machine_id;
        saveLicenses(licenses);
    }
    
    return res.json({
        valid: true,
        message: '验证成功',
        expire_date: license.expire_date,
        features: license.features || ['mass_send', 'schedule_send'],
        max_contacts: license.max_contacts || 1000
    });
});

// 获取所有激活码API（管理用）
app.get('/api/licenses', (req, res) => {
    const licenses = readLicenses();
    res.json({
        success: true,
        data: licenses
    });
});

// 删除激活码API（管理用）
app.delete('/api/licenses/:license_key', (req, res) => {
    const { license_key } = req.params;
    const licenses = readLicenses();
    const newLicenses = licenses.filter(l => l.license_key !== license_key);
    
    if (saveLicenses(newLicenses)) {
        res.json({
            success: true,
            message: '删除成功'
        });
    } else {
        res.status(500).json({
            success: false,
            message: '删除失败'
        });
    }
});

// 健康检查API
app.get('/api/health', (req, res) => {
    res.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        machine_id: generateMachineId()
    });
});

// 启动服务器
app.listen(PORT, () => {
    initLicenseFile();
    console.log(`卡密验证服务器运行在 http://localhost:${PORT}`);
    console.log(`健康检查: http://localhost:${PORT}/api/health`);
    console.log(`生成激活码: npm run generate`);
}); 